package com.roobtyan.todomemback.service.serviceImpl;

import com.roobtyan.todomemback.entity.Todo;
import com.roobtyan.todomemback.entity.TodoExample;
import com.roobtyan.todomemback.mapper.TodoMapper;
import com.roobtyan.todomemback.service.TodoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class TodoServiceImpl implements TodoService {
    @Resource
    private TodoMapper todoMapper;

    @Override
    public List<Todo> getAllDoingTodo() {
        TodoExample todoExample = new TodoExample();
        todoExample.setOrderByClause("create_time desc");
        TodoExample.Criteria criteria = todoExample.createCriteria();
        criteria.andStatusEqualTo(1);

        return todoMapper.selectByExample(todoExample);
    }

    @Override
    public List<Todo> getAllDoneTodo() {
        TodoExample todoExample = new TodoExample();
        todoExample.setOrderByClause("complete_time desc");
        TodoExample.Criteria criteria = todoExample.createCriteria();
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.DATE, -30);
        Date aMonth = instance.getTime();
        criteria.andStatusEqualTo(0).andCompleteTimeGreaterThan(aMonth);
        return todoMapper.selectByExample(todoExample);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addTodo(Todo todo) {
        try {
            todoMapper.insertSelective(todo);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTodo(Todo todo) {
        try {
            todoMapper.updateByPrimaryKeySelective(todo);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTodo(String todoId) {
        try {
            todoMapper.deleteByPrimaryKey(todoId);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean doneTodo(String todoId) {
        Todo todo = new Todo();
        todo.setStatus(0);
        todo.setId(todoId);
        todo.setCompleteTime(new Date());
        try {
            todoMapper.updateByPrimaryKeySelective(todo);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
